package com.lwh.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lwh.yygh.hosp.repository.DepartmentRepository;
import com.lwh.yygh.hosp.service.DepartmentService;
import com.lwh.yygh.model.hosp.Department;
import com.lwh.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author lwh
 * @date 2021/6/2 9:01
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;


    @Override
    public void save(Map<String, Object> map) {
        String s = JSONObject.toJSONString(map);
        Department department = JSONObject.parseObject(s,Department.class);

        //根据医院编号和课室编号进行查询
        Department departmentExist = departmentRepository
                .getDepartmentByHoscodeAndDepcode(department.getHoscode(),department.getDepcode());

        //判断
        if (departmentExist!=null) {
            departmentExist.setUpdateTime(new Date());
            departmentExist.setIsDeleted(0);
            departmentRepository.save(departmentExist);
        } else {
            department.setUpdateTime(new Date());
            department.setCreateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }


    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo queryVo) {
        //传教pageable对象，设置当前页和每页记录数
        //0是第一页
        Department department = new Department();
        BeanUtils.copyProperties(queryVo,department);
        department.setIsDeleted(0);


        Pageable pageable = PageRequest.of(page-1,limit);
        //创建Example对象
        ExampleMatcher matcher =ExampleMatcher.matching();
        matcher.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Department> example = Example.of(department,matcher);

        Page<Department> all = departmentRepository.findAll(example, pageable);
        return all;
    }


    @Override
    public void remove(String hoscode, String depcode) {
        Department department = departmentRepository.findDepartmentByHoscodeAndDepcode(hoscode,depcode);
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }
    }
}
